#pragma once

#include "bencode.hpp"

namespace bitgene {

/**
 * Remove .utf-8 keys in old BitComet torrent files.
 */
template <template <typename> class Traits>
void utf8(basic_bencode<Traits> &r)
{
	typedef typename basic_bencode<Traits>::integer_type integer_type;
	typedef typename basic_bencode<Traits>::string_type string_type;
	typedef typename basic_bencode<Traits>::list_type list_type;
	typedef typename basic_bencode<Traits>::dictionary_type dictionary_type;

	if (list_type *v = r.template pointer<list_type>())
	{
		for (typename list_type::iterator i = v->begin(); i != v->end(); ++i)
			utf8(*i);
	}
	else if (dictionary_type *v = r.template pointer<dictionary_type>())
	{
		dictionary_type d;
		for (typename dictionary_type::iterator i = v->begin(); i != v->end(); ++i)
		{
			const typename dictionary_type::key_type &key = i->first;
			if (key.size() > 6 && key.substr(key.size() - 6) == ".utf-8")
				d[key.substr(0, key.size() - 6)] = i->second;
			else if (v->find(key + ".utf-8") == v->end())
			{
				utf8(i->second);
				d[key] = i->second;
			}
		}
		v->swap(d);
	}
}

} // namespace bitgene
